const app = getApp(),
s = require("../../utils.js"),
i = require("../../wxParse/wxParse.js"),
t = require("../../api.js");
 

Page({
  data: {
    id:1,
    total_num:0,
    totalPrice:0,
    show:false,
    num:0,
    // g_num:0,
    page:1,
    store_id : 1,
    title : '',
    b_num:0,
    content: '',
    start_time : '',
    time:'',
    show:false,
    end_time: '',
    is_delete : 0,
    is_show : 1,
    addtime : '',
    sort: 1,
    see_num : 666,
    type : 1,
    bg_img: '',
    take_time : '',
    cover_img : '',
    img_list : '',
    res: [],
    goods_list:[],
    body:[],
    is_load: 1,
    carGoods: [],
    desc: ''
  },
  onLoad: function (a) {
    app.pageOnLoad(this, a);
    var id = 0;
    if (a.id > 0) {
      id = a.id;
    } else {
      var m = decodeURIComponent(a.scene);
      if (void 0 !== m) {
        var h = s.scene_decode(m);
        console.log('hh',h)
        if (h.id > 0) {
          id = h.id;
        }
      }
    }
    var that = this;
    if (id > 0) {
      this.setData({
        'id':id
      },function () {
        that.getList();
        that.getGoods();
        that.getBody();
      })
    }else {
      wx.showModal({
        title: '提示',
        content: '访问错误',
        showCancel: false,
        success: function () {
          wx.navigateBack({
            delta: 0,
          })
        }
      })
    }
  },
  getList: function () {
    var that = this;
    app.request({
      url: t.jielong.edit,
      data:{
        //获取对应的接龙id
        id:that.data.id
      },
      success: function(res) {
        if (res.data.code == 0) {
          var ctn = res.data.list1.content;
          i.wxParse("content", "html", ctn, that),
         that.setData({
            bg_img:res.data.list1.bg_img,
            cover_img:res.data.list1.cover_img,
            start_time:res.data.list1.start_time,
            end_time:res.data.list1.end_time,
            title:res.data.list1.title,
            addtime:res.data.list1.addtime,
            time:res.data.list1.time,
            take_time:res.data.list1.take_time,
            goods_list:res.data.goods_list,
            desc: res.data.list1.desc
        }),
        
        console.log(res.data.goods_list)
        }
      }
    })
  },
  getGoods:function(){
    var that = this;
    if (!that.data.is_load) {return false}
     wx.showLoading({
      title: '加载中',
    }),
    app.request({
      url: t.jielong.num,
      data:{
        //获取对应的接龙id
        id:that.data.id,
        page:that.data.page
      },
      success: function(res) {
        if (res.data.code == 0) {
        var new_res = that.data.res.concat(res.data.res);
         that.setData({
           res:new_res,
           page:++that.data.page,
           is_load:res.data.is_load == 1? 1:0
        }),
        
        console.log(res.data.res)
        }
      },
      complete: function () {
        wx.hideLoading()
      }
    })
  },
  getBody:function(){
    var ta = this;
    app.request({
      url:t.jielong.body,
      data:{
        //获取对应的接龙id
        id:ta.data.id
       
      },
      success:function(res){
        if(res.data.code == 0){
          ta.setData({
            b_num:res.data.b_num,
            body:res.data.body
          })
        }
        console.log(res.data.body)
      }
    })
  },
  goTop:  function(e)  {  //  一键回到顶部
    if  (wx.pageScrollTo)  {
        wx.pageScrollTo({
            scrollTop:  0
        })
    }  else  {
        wx.showModal({
            title:  '提示',
            content:  '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
        })
    }
},
  onShow: function(){
    app.pageOnShow(this);
  },
  getTotalPrice() {
    // 获取商品列表
    let goods_list = this.data.goods_list;                 
    let total = 0;
    let t_num = 0;
  // 循环列表得到每个数据
    for(let i = 0; i<goods_list.length; i++) {         
      // 所有价格加起来  
            total += goods_list[i].g_num * goods_list[i].price;   
            t_num += goods_list[i].g_num;
    }
      // 最后赋值到data中渲染到页面
    this.setData({                              
        goods_list: goods_list,
        totalPrice: total.toFixed(2),
        total_num: t_num.toFixed(0)
    });
  },
//上拉加载
  onReachBottom: function () {
    this.getGoods();
    },
  onShareAppMessage: function(tt) {
    var i = this;
    return {
      path: "/jielong/edit/index?id=" + i.data.id,
      imageUrl: i.data.bg_img,
      title: i.data.title ,
      success: function (t) {
        
      },
    };
  },
  onShareTimeline: function (tt) {
    var i = this;
    return {
      query:{
        id: i.data.id,
      },
      title: i.data.title ,
      imageUrl: i.data.bg_img,
    };
  },

  jia: function(t) {
      var a = this, o = t.currentTarget.dataset, r = a.data.goods_list;
      for (var s in r) if (parseInt(r[s].id) === parseInt(o.id)) {
          var e = r[s].num ? r[s].num + 1 : 1;
          if (e > JSON.parse(r[s].attr)[0].num) return void wx.showToast({
              title: "商品库存不足",
              image: "/images/icon-warning.png"
          });
          r[s].num = e;
          var d = a.data.carGoods, c = 1, n = o.price ? o.price : r[s].price;
          for (var u in d) {
              if (parseInt(d[u].goods_id) === parseInt(o.id) && 1 === d[u].attr.length) {
                  c = 0, d[u].num = e, d[u].goods_price = (d[u].num * d[u].price).toFixed(2);
                  break;
              }
              if (d[u].price == parseFloat(t.currentTarget.dataset.price)) {
                  c = 0, d[u].num = d[u].num + 1, d[u].goods_price = (d[u].num * d[u].price).toFixed(2);
                  break;
              }
          }
          if (1 === c || 0 === d.length) {
              var _ = JSON.parse(r[s].attr);
              d.push({
                  goods_id: parseInt(r[s].id),
                  attr: _[0].attr_list,
                  goods_name: r[s].name,
                  goods_price: n,
                  num: 1,
                  price: n
              });
          }
      }
      a.setData({
        carGoods: d,
        goods_list: r
      }), a.carStatistics();
  },
  carStatistics: function() {
      var t = this, a = t.data.carGoods;
      var o = 0, r = 0;
      for (var i in a) o += a[i].num, r = parseFloat(r) + parseFloat(a[i].goods_price);
      var s = {
          total_num: o,
          total_price: r.toFixed(2)
      };
      0 === o && t.hideGoodsModel(), t.setData({
          total: s
      });
  },
  hideGoodsModel: function() {
      this.setData({
          goodsModel: !1
      });
  },
  guigejian: function(t) {
      var a = this, o = a.data.checked_attr, r = a.data.carGoods, i = a.data.check_num ? --a.data.check_num : 1;
      a.data.currentGood;
      for (var s in r) {
          var e = [];
          for (var d in r[s].attr) e.push([ r[s].attr[d].attr_id, r[s].goods_id ]);
          if (e.sort().join() === o.sort().join()) return r[s].num > 0 && (r[s].num -= 1, 
          r[s].goods_price = (r[s].num * parseFloat(r[s].price)).toFixed(2)), a.setData({
              carGoods: r,
              check_goods_price: r[s].goods_price,
              check_num: i
          }), a.carStatistics();
      }
  },
  jian: function(t) {
      var a = this, o = t.currentTarget.dataset, r = a.data.goods_list;
      for (var s in r) if (parseInt(r[s].id) === parseInt(o.id)) {
          var e = r[s].num > 0 ? r[s].num - 1 : r[s].num;
          console.log(e);
          r[s].num = e;
          var d = a.data.carGoods;
          for (var c in d) {
              o.price ? o.price : r[s].price;
              if (parseInt(d[c].goods_id) === parseInt(o.id) && 1 === d[c].attr.length) { console.log('11111');
                  d[c].num = e, d[c].goods_price = (d[c].num * d[c].price).toFixed(2);
                  break;
              }
              if (d[c].price == parseFloat(t.currentTarget.dataset.price)) {
                  0, d[c].num > 0 && (d[c].num = d[c].num - 1, d[c].goods_price = (d[c].num * d[c].price).toFixed(2));
                  break;
              }
          }
      }
      console.log(d);
      a.setData({
          carGoods: d,
          goods_list: r
      }), a.carStatistics();
  },
  showDialogBtn: function(o) {
    var r = this, i = o.currentTarget.dataset;
    app.request({
        url: t.default.goods,
        data: {
            id: i.id
        },
        success: function(t) {
            0 == t.code && (r.setData({
                currentGood: t.data,
                goods_name: t.data.name,
                attr_group_list: t.data.attr_group_list,
                showModal: !0
            }), r.resetData(), r.updateData());
        }
    });
  },
  resetData: function() {
      this.setData({
          checked_attr: [],
          check_num: 0,
          check_goods_price: 0,
          temporaryGood: {
              price: "0.00"
          }
      });
  },
  updateData: function() {
      var t = this, a = t.data.currentGood, o = t.data.carGoods, r = JSON.parse(a.attr), i = a.attr_group_list;
      for (var s in r) {
          var e = [];
          for (var d in r[s].attr_list) e.push([ r[s].attr_list[d].attr_id, a.id ]);
          for (var c in o) {
              var n = [];
              for (var u in o[c].attr) n.push([ o[c].attr[u].attr_id, o[c].goods_id ]);
              if (e.sort().join() === n.sort().join()) {
                  for (var _ in i) for (var g in i[_].attr_list) for (var l in e) {
                      if (parseInt(i[_].attr_list[g].attr_id) === parseInt(e[l])) {
                          i[_].attr_list[g].checked = !0;
                          break;
                      }
                      i[_].attr_list[g].checked = !1;
                  }
                  var h = {
                      price: o[c].price
                  };
                  return void t.setData({
                      attr_group_list: i,
                      check_num: o[c].num,
                      check_goods_price: o[c].goods_price,
                      checked_attr: e,
                      temporaryGood: h
                  });
              }
          }
      }
  },

  attrClick: function(t) {
      var a = this, o = t.target.dataset.groupId, r = t.target.dataset.id, i = a.data.attr_group_list, s = a.data.currentGood;
      for (var e in i) if (i[e].attr_group_id == o) for (var d in i[e].attr_list) i[e].attr_list[d].attr_id == r ? i[e].attr_list[d].checked = !0 : i[e].attr_list[d].checked = !1;
      var c = [];
      for (var e in i) for (var d in i[e].attr_list) !0 === i[e].attr_list[d].checked && c.push([ i[e].attr_list[d].attr_id, s.id ]);
      var n = JSON.parse(a.data.currentGood.attr), u = a.data.temporaryGood;
      for (var _ in n) {
          var g = [];
          for (var l in n[_].attr_list) g.push([ n[_].attr_list[l].attr_id, s.id ]);
          if (g.sort().join() === c.sort().join()) {
              if (0 === parseInt(n[_].num)) return void wx.showToast({
                  title: "商品库存不足，请选择其它规格或数量",
                  image: "/images/icon-warning.png"
              });
              u = parseFloat(n[_].price) ? {
                  price: n[_].price.toFixed(2)
              } : {
                  price: s.price.toFixed(2)
              };
          }
      }
      a.resetData(), a.checkUpdateData(c), a.setData({
          attr_group_list: i,
          temporaryGood: u,
          checked_attr: c
      });
  },
  checkUpdateData: function(t) {
      var a = this, o = a.data.carGoods;
      for (var r in o) {
          var i = [];
          for (var s in o[r].attr) i.push([ o[r].attr[s].attr_id, o[r].goods_id ]);
          i.sort().join() === t.sort().join() && a.setData({
              check_num: o[r].num,
              check_goods_price: o[r].goods_price
          });
      }
  },
  close_box: function(t) {
      this.setData({
          showModal: !1
      });
  },

  onConfirm: function(t) {
      var a = this, o = a.data.attr_group_list, r = a.data.checked_attr, i = a.data.currentGood;
      if (r.length === o.length) {
          var s = a.data.check_num ? a.data.check_num + 1 : 1, e = JSON.parse(i.attr);
          for (var d in e) {
              var c = [];
              for (var n in e[d].attr_list) if (c.push([ e[d].attr_list[n].attr_id, i.id ]), c.sort().join() === r.sort().join()) {
                  var u = e[d].price ? e[d].price : i.price, _ = e[d].attr_list;
                  if (s > e[d].num) return void wx.showToast({
                      title: "商品库存不足",
                      image: "/images/icon-warning.png"
                  });
              }
          }
          var g = a.data.carGoods, l = 1, h = (parseFloat(u) * s).toFixed(2);
          for (var p in g) {
              var f = [];
              for (var v in g[p].attr) f.push([ g[p].attr[v].attr_id, g[p].goods_id ]);
              if (f.sort().join() === r.sort().join()) {
                  l = 0, g[p].num = g[p].num + 1, g[p].goods_price = (parseFloat(u) * g[p].num).toFixed(2);
                  break;
              }
          }
          1 !== l && 0 !== g.length || g.push({
              goods_id: i.id,
              attr: _,
              goods_name: i.name,
              goods_price: u,
              num: 1,
              price: u
          }), a.setData({
              carGoods: g,
              check_goods_price: h,
              check_num: s
          }), a.carStatistics();
      } else wx.showToast({
          title: "请选择规格",
          image: "/images/icon-warning.png"
      });
  },
  buynow: function(t) {
      var a = this, o = a.data.carGoods;
      a.data.goodsModel;
      a.setData({
          goodsModel: !1
      });
      for (var r = o.length, i = [], s = [], e = 0; e < r; e++) 0 != o[e].num && (s = {
          goods_id: o[e].goods_id,
          num: o[e].num,
          attr: o[e].attr
      }, i.push(s));
      var d = [];
      d.push({
          mch_id: 0,
          goods_list: i
      }), wx.navigateTo({
          url: "/pages/new-order-submit/new-order-submit?mch_list=" + JSON.stringify(d)
      });
  },
    // 一键复制事件
    copyBtn: function (e) {

      var obf_data = { i_1: '1️⃣', i_2: '2️⃣', i_3: '3️⃣', i_4: '4️⃣', i_5: '5️⃣', i_6: '6️⃣', i_7: '7️⃣', i_8: '8️⃣', i_9: '9️⃣', i_0: '0️⃣'} ;
      var order_list = this.data.res;
      if (!order_list || order_list.length < 1) {
        wx.showToast({
          icon:"none",
          title: '还没有订单',
        });
        return false;
      }
      var store_name = wx.getStorageSync('store_name')
      var data = " 🌹 " + store_name + this.data.title +'群接龙' + " 🌹 " + ' \n';
      for (var i = 0; i < order_list.length; i++) {
        // 商品名称 
        var goods_info = '';
        goods_info += "💵" + order_list[i].goods_name + '\n';
  
        var h = i + 1;
        if (h < 100) {
          var ten = Math.floor(h / 10);
          var num = h % 10;
          data += obf_data['i_' + ten] + ' ' + obf_data['i_' + num] + order_list[i].nickname + '\n' + goods_info;
        }
      }
      var that = this;
      wx.setClipboardData({
        //准备复制的数据
        data: data,
        success: function (res) {
          wx.showToast({
            title: '复制成功',
          });
        }
      });
    },
})
